package com.github.defense.plugin.gray;

import com.github.defense.plugin.gray.constants.GrayClientConstant;
import org.springframework.cloud.commons.util.SpringFactoryImportSelector;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.util.StringUtils;

import java.util.Properties;

/**
 * 如果没有开启灰度开关则系统默认强行开启
 * 默认启用灰度
 *
 * @Author: lettger
 * @Date: 2021/6/5 11:06 上午
 */
@Order(Ordered.LOWEST_PRECEDENCE - 1000)
public class GrayClientImportSelector extends SpringFactoryImportSelector<EnableGrayClient> {

    @Override
    public String[] selectImports(AnnotationMetadata metadata) {
        String[] imports = super.selectImports(metadata);
        Environment env = getEnvironment();
        String graySwitch = env.getProperty(GrayClientConstant.GRAY_CLIENT_ENABLE);
        if (StringUtils.isEmpty(graySwitch)) {
            if (ConfigurableEnvironment.class.isInstance(env)) {
                ConfigurableEnvironment environment = (ConfigurableEnvironment) env;
                MutablePropertySources mutablePropertySources = environment.getPropertySources();
                Properties properties = new Properties();
                properties.put(GrayClientConstant.GRAY_CLIENT_ENABLE, "true");
                mutablePropertySources.addLast(new PropertiesPropertySource("defaultProperties", properties));
            }
        }
        return imports;
    }

    @Override
    protected boolean isEnabled() {
        return false;
    }

    @Override
    protected boolean hasDefaultFactory() {
        return true;
    }
}
